<?php
namespace iBrand\Shop\Core\Service;

/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2018/3/20
 * Time: 16:06
 */

use iBrand\Shop\Core\Models\O2oGoods;
use iBrand\Wechat\Server\Wx\MiniAccessToken;
use Intervention\Image\Facades\Image;

class WeProgramService
{
    protected $token;
    const API_WXACODE_GET = 'https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token='; //适用于需要的码数量极多，或仅临时使用的业务场景

    public function __construct()
    {
        $this->token = new MiniAccessToken(settings('mini_program_app_id'), settings('mini_program_secret'));
        //$this->token = new AccessToken('wx2a84b66430c95b11', '349b425c9ce071fe9ee0c2d392f5e50e');
    }


    protected function getAccessToken()
    {
        return $this->token->getToken();
    }

    /**
     * 生成小程序指定页面二维码
     * @param $shop_id :门店ID
     * @param $page :页面url
     * @param int $width
     * @return bool|string
     */
    public function getWxaCodeUrl($page, $shop_id, $goods_id = 0, $width = 430)
    {
        if ($goods_id AND $goods = O2oGoods::where('goods_id', $goods_id)->where('shop_id', $shop_id)->first() AND $goods->mini_qrcode) {
            return [$goods->mini_qrcode, $goods->mini_qrcode_name];
        }

        $option = [
            'path' => $page,
            'width' => $width
        ];
        $body = mini_curl(self::API_WXACODE_GET . $this->getAccessToken(), $option);
        if (str_contains('errcode', $body)) {
            return false;
        }

        $ext = '.jpg';
        $file_name = md5(time() . rand(0, 10000));
        $savePath = 'public/o2o/wxa_code/' . $shop_id . '/' . $file_name . $ext;
        $result = \Storage::put($savePath, $body);
        if ($result) {
            $title_url = '';
            $url = '/storage/o2o/wxa_code/' . $shop_id . '/' . $file_name . $ext;
            if ($goods_id) {
                $goods = O2oGoods::where('goods_id', $goods_id)->where('shop_id', $shop_id)->first();

                $titleImg = $this->makeTitleImg( $goods->goods->name, $shop_id);
                $this->makeShareImg($titleImg, env('APP_URL') . $url, storage_path('app/public/o2o/wxa_code/' . $shop_id . '/' . $file_name . '_t' . $ext));
                $title_url = '/storage/o2o/wxa_code/' . $shop_id . '/' . $file_name . '_t' . $ext;

                $goods->mini_qrcode = $url;
                $goods->mini_qrcode_name = $title_url;
                $goods->save();
            }

            return [$url, $title_url];
        }
        return false;
    }

    
    /**
     * 合成图片
     * @param $topImg
     * @param $textImg
     * @param $saveName
     */
    private function makeShareImg($topImg, $textImg, $saveName)
    {

        $path_1 = $topImg; //第一张图
        $dst_info = getimagesize($path_1);

        $path_2 = $textImg; //第2张图
        $dst_info_2 = getimagesize($path_2);
// 创建图片对象
        $image_1 = imagecreatefromjpeg($path_1);
        $image_2 = imagecreatefromjpeg($path_2);
// 创建真彩画布
        $image_3 = imageCreatetruecolor($dst_info[0], $dst_info_2[1] + 80);
// 为真彩画布创建白色背景
        $color = imagecolorallocate($image_3, 255, 255, 255);
        imagefill($image_3, 0, 0, $color);
// 设置透明
        imageColorTransparent($image_3, $color);
// 复制图片一到真彩画布中（重新取样-获取透明图片）
        imagecopyresampled($image_3, $image_1, 0, 0, 0, 0, imagesx($image_1), imagesy($image_1), imagesx($image_1), imagesy($image_1));
// 与图片二合成
        imagecopymerge($image_3, $image_2, 0, $dst_info[1], 0, 0, imagesx($image_2), imagesy($image_2), 100);
// 输出合成图片
        imagejpeg($image_3, $saveName);

    }

    private function makeTitleImg($goods_name, $shop_id)
    {
        $tempName = md5(time() . rand(0, 10000)) . '_temp.jpg';
        $img = Image::canvas(470, 80, '#ffffff');
        $img->text($goods_name, 20, 70, function ($font) {
            $font->file(public_path('assets/backend/distribution/simsun.ttf'));
            $font->size(18);
            $font->color('#000000');
        });
        $path = storage_path('app/public/o2o/wxa_code/' . $shop_id . '/' . $tempName);
        $img->save($path);
        return $path;

    }
}